<?php

namespace app\api\controller;

use app\admin\controller\Prize;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Db;
use think\Exception;
use think\Validate;
use app\admin\model\User as UserModel;
use app\admin\model\Follow;
use app\admin\model\Shop;
use app\admin\model\MpJson;
use app\admin\model\Feedback;
use app\admin\model\MpMp;
use app\admin\model\MpType;
use app\admin\model\MpMpj;
use app\admin\model\ProductViewLog;
use app\admin\model\MpClick;
use app\admin\model\UserCollect;
use app\admin\model\UserAddress;
use app\admin\model\MpLeaveWord;
use app\admin\model\Community;
use app\admin\model\Visit;
use app\admin\model\AreaWorldwide;
use app\admin\model\Product;
use app\admin\model\ProductMessage;
use app\admin\model\UserRoseLog;
use app\admin\model\ConfigData;
use app\admin\model\ChatMessage;
use app\admin\model\ProductWish;
use app\admin\model\MobileCode;
use app\admin\model\UserReport;
use app\admin\model\GroupChat;
use app\admin\model\GroupChatUser;
use getui\GeTui;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['get_mp_info','add_mp_click','user_lick'];

	public function _initialize(){
		$action = request()->action();
	
		if(!in_array($action,$this->noNeedLogin)){
			$ignore = array('host','accept','content-length','content-type');
			$headers = array();
			if($this->request->request('token')){
                $headers['token'] = $this->request->request('token');
            }else{
                foreach($_SERVER as $key=>$value){
                    if(substr($key, 0, 5)==='HTTP_'){
                        $key = substr($key, 5);
                        $key = str_replace('_', ' ', $key);
                        $key = str_replace(' ', '-', $key);
                        $key = strtolower($key);
                        if(!in_array($key, $ignore)){
                            $headers[$key] = $value;
                        }
                    }
                }
            }
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=UserModel::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
            if($this->user['status'] != 1){
                $this->error('账号异常');
            }
			UserModel::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
	}

    //获取我的名片分类
    public function getType(){
        $list = MpType::select();
        $this->success('操作成功',$list);
    }

    public function feedback_save(){
        $data['mobile'] = $this->request->request('mobile','');
        $data['content'] = $this->request->request('content','');
        $data['imgs'] = $this->request->request('imgs','');
        $data['user_id'] = $this->user['id'];
        $data['add_time'] = time();
        Feedback::insert($data);
        $this->success('操作成功');
    }

    

    //获取我的名片分类	
    public function getMpjList(){
        $title = $this->request->request('title','');
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $where = ['a.user_id'=>$this->user['id']];
        if($title){
            $where['b.username|b.company'] = ['like','%'.$title.'%'];
        }
        $list = MpMpj::alias('a')
            ->field("a.*,b.avatar,b.username,b.company,b.type,b.type_id")
            ->join("mp_mp b","b.id = a.mp_id")
            ->where($where)
            ->limit(($page-1)*$pagesize,$pagesize)
            ->order('a.add_time desc')
            ->select();
        foreach ($list as &$v) {
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $v['type_name'] = MpType::where(['id'=>$v['type_id']])->value('name');
        }
        $this->success('操作成功',$list);
    }

    //获取我的名片
    public function getMpList(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $where = ['user_id'=>$this->user['id'],'status'=>1];
        $list = MpMp::where($where)->limit(($page-1)*$pagesize,$pagesize)->order('add_time desc')->select();
        foreach ($list as &$v) {
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $v['type_name'] = MpType::where(['id'=>$v['type_id']])->value('name');
        }
        $this->success('操作成功',$list);
    }

    //获取名片详情
    public function get_mp_info(){
        $id = $this->request->request('id','');
        $token = $this->request->request('token','');
        
        
        if(!$id){
            $this->error('参数错误');
        }
        $info = MpMp::where(['id'=>$id,'status'=>1])->find();
        if(!$info){
            $this->error('参数错误');
        }

		$info['serve_imgs_list'] = '';
        if($info['serve_imgs']){
            $info['serve_imgs_list'] = explode(',',$info['serve_imgs']);
        }
        
        $info['wx_img_list'] = '';
        if($info['wx_img']){
            $info['wx_img_list'] = explode(',',$info['wx_img']);
        }
        $info['brand_imgs_list'] = '';
        if($info['brand_imgs']){
            $info['brand_imgs_list'] = explode(',',$info['brand_imgs']);
        }
        $info['case_imgs_list'] = '';
        if($info['case_imgs']){
            $info['case_imgs_list'] = explode(',',$info['case_imgs']);
        }
        
        
        
        $module_json_id = explode(',,,,',$info['module_json_id']);
        $module_json_name = explode(',,,,',$info['module_json_name']);
        $module_json_type = explode(',,,,',$info['module_json_type']);
        $module_json_status = explode(',,,,',$info['module_json_status']);
        $module_json_zdy_title = explode(',,,,',$info['module_json_zdy_title']);
        $module_json_text = explode(',,,,',$info['module_json_text']);
        $module_json_text_json = explode(',,,,',$info['module_json_text_json']);
        
        $arr = [];
        for ($i = 0; $i < count($module_json_id); $i++) {
            $category1 = [];
            $category = [];
            $json = json_decode(htmlspecialchars_decode($module_json_text_json[$i]),true);
            if($module_json_type[$i] == 4){
               
                $category[] = ['name'=>'全部'];
                foreach ($json as $v) {
                    if (!empty($v['category']) && !in_array($v['category'], $category1)) {
                        $category[] = ['name'=>$v['category']];
                        $category1[] = $v['category'];
                    }
                }
            }
            $text = htmlspecialchars_decode($module_json_text[$i]);
            if(!(!$text || $text == 'undefined')){
                $arr[] = [
                    'id'=>$module_json_id[$i],
                    'name'=>$module_json_name[$i],
                    'type'=>$module_json_type[$i],
                    'status'=>$module_json_status[$i],
                    'zdy_title'=>$module_json_zdy_title[$i],
                    'text'=>htmlspecialchars_decode($module_json_text[$i]),
                    'text_json'=>htmlspecialchars_decode($module_json_text_json[$i]),
                    'json'=>$json,
                    'category'=>$category,
                    'category_arr'=>$json,
                ];
            }
        }
        $info['price'] =  MpType::where(['id'=>$info['type_id']])->value('price');
        $info['mp_json'] = MpJson::where(['mp_id'=>$info['id']])->order('id desc')->find();
        $info['visit_num'] = MpClick::where(['mp_id'=>$info['id']])->group('mp_id')->count();
        $arrs = MpClick::where(['mp_id'=>$info['id'],'user_id'=>['>',0]])->group('mp_id')->limit(0,5)->select();
        $arrList = [];
        if($arrs){
            foreach ($arrs as $v) {
                $arrList[] = ['url'=>UserModel::where(['id'=>$v['user_id']])->value('avatar')];
            }
        }
        $info['arrList'] = $arrList;
        $info['module_json_arr'] = $arr;
        $info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);
        MpMp::where(['id'=>$id])->update(['browse_num'=>$info['browse_num']+1]);

        $MpLeaveWord = MpLeaveWord::where(['mp_id'=>$info['id']])->order('add_time desc')->limit(0,5)->select();
        if($MpLeaveWord){
            foreach ($MpLeaveWord as &$v) {
                $v['add_time']=timeago($v['add_time']);
			    $v['user']	=UserModel::field('id,avatar,nickname')->where(array('id'=>$v['user_id']))->find();
            }
        }else{
            $MpLeaveWord = '';
        }
        $info['mp_leave_word'] = $MpLeaveWord;

        $this->success('操作成功',$info);
    }
    
    
    //点赞
    public function user_lick(){
        $mp_id = $this->request->request('mp_id',0);
        $type_id = $this->request->request('type_id',0);
        if($type_id >0){
            $info = MpType::where(['id'=>$type_id])->find();
            if($info){
                MpType::where(['id'=>$type_id])->update(['like_num'=>$info['like_num']+1]);
            }
            
        }else{
            $info = MpMp::where(['id'=>$mp_id,'status'=>1])->find();
            if($info){
                MpMp::where(['id'=>$mp_id])->update(['like_num'=>$info['like_num']+1]);
            }
           
        }
       
    }
    
    //记录用户访问和点击
    public function add_mp_click(){
        $token = $this->request->request('token','');
        $type = $this->request->request('type',1);
        $id = $this->request->request('id',1);
        $arr = [
            'mp_id'=>$id,
            'type'=>$type,
            'add_time'=>time()
        ];
        if($token){
            $arr['user_id'] = UserModel::where(['token'=>$token])->value('id');
        }
        $res = MpClick::insert($arr);
        if($res){
            $this->success('操作成功');
        }
    }


    //获取名片详情
    public function add_sc(){
        $mp_id = $this->request->request('mp_id','');
        $status = $this->request->request('status','');
        if($status == 1){ //收藏
            $info = MpMpj::where(['user_id'=>$this->user['id'],'mp_id'=>$mp_id])->find();
            if(!$info){
                MpMpj::insert(['user_id'=>$this->user['id'],'add_time'=>time(),'mp_id'=>$mp_id]);
            }else{
                MpMpj::where(['id'=>$info['id']])->update(['status'=>1]);
            }
        }else{ // 取消收藏
            $info = MpMpj::where(['user_id'=>$this->user['id'],'mp_id'=>$mp_id])->find();
            if($info){
                MpMpj::where(['id'=>$info['id']])->update(['status'=>-1]);
            }
        }
        $this->success('操作成功',$info);
    }

    //获取留言列表
    public function getMpLeaveWordList(){
        $mp_id = $this->request->request('mp_id','');
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $where = [
            'user_id'=>$this->user['id']
        ];
        if($mp_id){
            $where['mp_id'] = $mp_id;
        }
		$list=MpLeaveWord::where($where)->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();

        foreach($list as &$v){
			$v['add_time']=timeago($v['add_time']);
			$v['user']	=UserModel::field('id,avatar,nickname')->where(array('id'=>$v['user_id']))->find();
		}
        $this->success('获取成功',['list'=>$list,'total'=>count($list)]);
    }

    //发布留言
    public function addMpLeaveWord(){
        $mp_id = $this->request->request('mp_id','');
        $username = $this->request->request('username','');
        $phone = $this->request->request('phone','');
        $content = $this->request->request('content','');
        if(!$mp_id){
            $this->error('参数错误');
        }
        if(!$username){
            $this->error('姓名不可为空');
        }
        if(empty($phone) || (!check_phone($phone))){
            $this->error('请输入有效的手机号码');
		}
        if(!$content){
            $this->error('留言内容不可为空');
        }
        $arr = ['mp_id'=>$mp_id,'username'=>$username,'phone'=>$phone,'content'=>$content,'add_time'=>time(),'user_id'=>$this->user['id']];
        $res = MpLeaveWord::insert($arr);
        if($res){
            $arr['add_time']=timeago($arr['add_time']);
            $arr['user']	=UserModel::field('id,avatar,nickname')->where(array('id'=>$arr['user_id']))->find();
            $this->success('留言成功',$arr);
        }else{
            $this->error('留言失败');
        }
    }


    //获取新消息
    public function getmessage(){
        $product_id = $this->request->request('id',0);
        $wish_id = $this->request->request('wish_id',0);
        $sort = $this->request->request('sort','');
        $js_user_id = $this->request->request('js_user_id',0);
        $is_group_chat = $this->request->request('is_group_chat',0);
        if($is_group_chat){
            $where = [
                'status'=>1,
                'sort'=>$sort
            ];
            $list = ChatMessage::where($where)->order('add_time desc')->limit(0,1)->select();
        }else{
            if(!$sort){
                $where = [
                    'status'=>1,
                    'js_user_id'=>$this->user['id'],
                    'product_id'=>$product_id,
                    'wish_id'=>$wish_id,
                    'is_read'=>0,
                    'user_id'=>$js_user_id
                ];
            }else{
                $where = [
                    'status'=>1,
                    'js_user_id'=>$this->user['id'],
                    'product_id'=>$product_id,
                    'wish_id'=>$wish_id,
                    'is_read'=>0,
                    'sort'=>$sort,
                ];
            }
            $list = ChatMessage::where($where)->order('add_time asc')->select();
        }
       
        $ids = [];
        if($list){
            $avatar = UserModel::where(['id'=>$this->user['id']])->value('avatar');
            $last_time = 0;
            foreach ($list as &$v) {
                //查看用户信息
                if($v['is_read'] == 0){
                    //如果有未读消息则更新为已读
                    $ids[] = $v['id'];
                }
                $where = ['id'=>$v['user_id']];
                $v['avatar'] = $avatar;
                $v['user'] = UserModel::field('id,avatar,nickname')->where($where)->find();
                $v['time'] = '';
                if(!$last_time){
                    $v['time'] =  date('m-d H:i',$v['add_time']);
                    $last_time = $v['add_time'];
                }elseif(($v['add_time'] - $last_time) > 7600){
                    $v['time'] =  date('m-d H:i',$v['add_time']);
                    $last_time = $v['add_time'];
                }

                if($v['type'] == 1){ //文字
                    //判断发布文字有多少个字
                    $len = mb_strlen($v['content'], 'UTF-8');
                    $v['len'] = 135;
                    if($len > 16 && $len <= 32){
                        $v['len'] = 170;
                    }elseif($len > 32 && $len <= 48){
                        $v['len'] = 210;
                    }elseif($len > 48 && $len <= 64){
                        $v['len'] = 250;
                    }elseif($len > 64 && $len <= 80){
                        $v['len'] = 290;
                    }elseif($len > 80 && $len <= 96){
                        $v['len'] = 330;
                    }elseif($len > 96 && $len <= 122){
                        $v['len'] = 370;
                    }elseif($len > 122 && $len <= 138){
                        $v['len'] = 410;
                    }elseif($len > 138){
                        $v['len'] = 450;
                    }
                }elseif($v['type'] == 2){ //图片
                    $v['len'] = 290;
                }elseif($v['type'] == 3){ //商品
                    $v['len'] = 270;
                    $v['product'] = Product::field('id,video_img,title,price')->where(['id'=>$v['goods_id']])->find();
                }
                if($v['time']){
                    $v['len'] =  $v['len'] + 40;
                }
            }
        }
        if($ids){
            ChatMessage::where(['id'=>['in',$ids]])->update(['is_read'=>1]);
        }
        $this->success('操作成功',$list);
    }

    //添加访问记录
    public function add_visit(){
	    $visit_user_id=$this->request->request('visit_user_id');
	    if($visit_user_id!=$this->user['id']){
	        $visit=Visit::where(array('user_id'=>$this->user['id'],'visit_user_id'=>$visit_user_id))->find();
	        if($visit){
	            Visit::where(array('user_id'=>$this->user['id'],'visit_user_id'=>$visit_user_id))->update(array('add_time'=>time()));
	        }else{
	            Visit::insert(array('user_id'=>$this->user['id'],'visit_user_id'=>$visit_user_id,'add_time'=>time()));
	        }
	    }
        $this->success('操作成功');
	}
    //点击关注
	public function follow(){
		$user_id=$this->request->request('item_user_id',0);
		if(!$user_id){
            $this->error('缺少参数');
		}
		$u=UserModel::where(array('id'=>$user_id))->find();
		if(!$u){
            $this->error('关注对象用户不存在');
		}
		$fans_user_id=$this->user['id'];
		$follow=Follow::where(array('user_id'=>$user_id,'fans_user_id'=>$fans_user_id))->find();
		if(!$follow){
			Follow::insert(array('user_id'=>$user_id,'fans_user_id'=>$fans_user_id,'is_read'=>1,'add_time'=>time()));
			UserModel::where(array('id'=>$this->user['id']))->update(array('read_message'=>1));
            $this->success('关注成功');
		}else{
            $this->success('已关注');
		}
	}
    //获取用户地址
	public function default_user_address(){
		$address_id	=	$this->request->request('address_id','');
        if($address_id){
            $address	=	UserAddress::where(array('user_id'=>$this->user['id'],'id'=>$address_id))->find();
        }else{
            $address	=	UserAddress::where(array('user_id'=>$this->user['id'],'is_default'=>1))->find();		
        }
		if(!$address){
			$address =	UserAddress::where(array('user_id'=>$this->user['id']))->order('add_time desc')->limit(0,1)->find();				
		}   
        if($address){
            $address['yg'] = json_decode($address['yg'],true);
        }

        $this->success('操作成功',$address);
	}
    //获取用户地址列表
    public function user_address(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $list = UserAddress::where(['user_id'=>$this->user['id']])->order('is_default desc,add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
        foreach ($list as &$v) {
            if($v['yg']){
                $v['yg'] = json_decode($v['yg']);
            }
        }
        $this->success('操作成功',$list);
    }
    
    //添加用户地址
	public function user_address_save(){
		$id	=	$this->request->request('id','');
		$name	=	$this->request->request('name','');
		$mobile	=	$this->request->request('mobile','');
		$province	=	$this->request->request('province','');
		$city	=	$this->request->request('city','');
		$district	=	$this->request->request('district','');
		$address	=	$this->request->request('address','');
		$postcode	=	$this->request->request('postcode','');
		$latitude	=	$this->request->request('latitude','');
		$longitude	=	$this->request->request('longitude','');
		$is_default	=	$this->request->request('is_default','');
		$is_foreign	=	$this->request->request('is_foreign','中国');
		$select	=	$this->request->request('select','');
		$line_1	=	$this->request->request('line_1','');
		$line_2	=	$this->request->request('line_2','');
		$town	=	$this->request->request('town','');
		$county	=	$this->request->request('county','');
		$zhi	=	$this->request->request('zhi','');
		$zong_address	=	$this->request->request('zong_address','');

        if(empty($name)){
            $this->error('联系人不能为空');
		}
        if(empty($mobile) || (!check_phone($mobile) && $is_foreign == '中国')){
            $this->error('请输入有效的手机号码');
		}
        if($zong_address && (empty($province) && empty($city) && empty($district))){
            if (strpos($zong_address, '内蒙古自治区') !== false) {
                $res = explode('古自治区',$zong_address); //['湖北',武汉市汉阳区芳草路1号]
                $province = $res[0].'古自治区';
            }else{
                $res = explode('省',$zong_address); //['湖北',武汉市汉阳区芳草路1号]
                $province = $res[0].'省';
            }
            //"湖北省武汉市汉阳区芳草路1号"
            $res = explode('市',$res[1]); //['武汉',汉阳区芳草路1号]
            $city = $res[0].'市';
            $str = $res[1];
            $subStr = "区";
            if (strpos($str, $subStr) !== false) {
                //存在区
                $res = explode('区',$res[1]); //['武汉',汉阳区芳草路1号]
                $district = $res[0].'区';
            } else {
                //没有区找县
                $subStr = "县";
                if (strpos($str, $subStr) !== false) {
                    //存在县
                    $res = explode('县',$res[1]); //['武汉',汉阳区芳草路1号]
                    $district = $res[0].'县';
                }
            }
        }else{  
            if( $is_foreign == '中国' && (empty($province) || empty($city) || empty($district) || $province == 'undefined' || $city == 'undefined' || $district == 'undefined')){
                $this->error('所在地区错误');
            }
        }
        if($is_foreign == '中国' && empty($address)){
            $this->error('详细地址不能为空');
		}
        if($is_foreign == '英国' && !$postcode){
            $this->error('邮编不能为空');
		}
        if($postcode){
            $a = str_replace(" ", "", $postcode);
            if(strlen($a) >= 4 && strlen($a) <= 8){
                if(is_numeric($a[0])) $this->error('请输入正确邮编');
                if(is_numeric($a[strlen($a)-1])) $this->error('请输入正确邮编');

                if(strlen($a) == 4){
                    if(is_english($a[1])) $this->error('请输入正确邮编');
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                }elseif(strlen($a) == 5){
                    //第一个和最后一个肯定是
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                }elseif(strlen($a) == 6){
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                    if(is_english($a[3])) $this->error('请输入正确邮编');
                }elseif(strlen($a) == 7){
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                    if(is_english($a[3])) $this->error('请输入正确邮编');
                    if(is_english($a[4])) $this->error('请输入正确邮编');
                }elseif(strlen($a) == 8){
                    if(is_numeric($a[1])) $this->error('请输入正确邮编');
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                    if(is_english($a[3])) $this->error('请输入正确邮编');
                    if(is_english($a[4])) $this->error('请输入正确邮编');
                    if(is_english($a[5])) $this->error('请输入正确邮编');
                    if(is_numeric($a[6])) $this->error('请输入正确邮编');
                }
            }else{
                $this->error('请输入正确邮编');
            }
        }
        if($is_foreign != '中国'){
            $arr = explode('-',$select);
            $district = '';
            $city = '';
            if(count($arr) == 1){
                $province = $arr[0];
            }elseif(count($arr) == 2){
                $province = $arr[0];
                $city = $arr[1];
            }
            $yg = [
                'line_1'=>$line_1,
                'line_2'=>$line_2,
                'town'=>$town,
                'county'=>$county,
                'postcode'=>$postcode,
                'zhi'=>$zhi
            ];
            $yg = json_encode($yg,JSON_UNESCAPED_UNICODE);
        }
        UserModel::where(['id'=>$this->user['id']])->update(['country'=>$is_foreign]);
        $arr = [
            'user_id'=>$this->user['id'],
            'name'=>$name,
            'mobile'=>$mobile,
            'province'=>$province,
            'city'=>$city,
            'district'=>$district,
            'address'=>$address,
            'longitude'=>$longitude,
            'latitude'=>$latitude,
            'postcode'=>$postcode,
            'is_default'=>$is_default,
            'add_time'=>time(),
            'is_foreign'=>$is_foreign == '中国' ? 0 : 1,
            'country'=>$is_foreign,
            'country_id'=>AreaWorldwide::where(['name'=>$is_foreign])->value('id'),
            'yg'=>$is_foreign == '英国' ? $yg : ''
        ];
        if($is_default == 1){
            UserAddress::where(['user_id'=>$this->user['id']])->update(['is_default'=>0]);
        }else{
            $info = UserAddress::where(['user_id'=>$this->user['id']])->find();
            if(!$info){
                $arr['is_default'] = 1;
            }
            
            if($arr['is_default'] == 0){
                $info = UserAddress::where(['user_id'=>$this->user['id'],'is_default'=>1])->find();
                if(!$info){
                    $this->error('最少存在一个默认地址!');
                }
            }
        }
        if($id){
            $res	=	UserAddress::where(['id'=>$id])->update($arr);
        }else{
            $res = $id	=	UserAddress::insertGetId($arr);
        }

		if($res){
            $this->success('操作成功',$id);
		}else{
            $this->success('操作失败');
        }
        
	}
    //取消关注
	public function follow_cancel(){
		$user_id		=$this->request->request('item_user_id',0);
		$fans_user_id	=$this->user['id'];
		Follow::where(array('user_id'=>$user_id,'fans_user_id'=>$fans_user_id))->delete();
        $this->success('操作成功');
	}
    //聊天举报
    public function user_report(){
        $by_user_id=$this->request->request('by_user_id',0);
        $sort=$this->request->request('sort',0);
        $type=$this->request->request('type',0);
        $product_id=$this->request->request('product_id',0);
        $wish_id=$this->request->request('wish_id',0);
        $community_id=$this->request->request('community_id',0);
        if($product_id || $wish_id || $community_id){
            $data = [
                'user_id'=>$this->user['id'],
                'add_time'=>time(),
                'product_id'=>$product_id,
                'wish_id'=>$wish_id,
                'community_id'=>$community_id,
               
            ];
            if($type == 2){
                $data['by_user_id'] =  $by_user_id;
            }
        }else{
            $info = UserReport::where(['sort'=>$sort])->find();
            if($info){
                $this->success('操作成功');
            }
            $data = [
                'user_id'=>$this->user['id'],
                'by_user_id'=>$by_user_id,
                'add_time'=>time(),
                'sort'=>$sort
            ];
        }
        UserReport::insert($data);
        $this->success('操作成功');
    }

    //通过邮编搜索具体地址
    public function getFetchify(){
        $postcode = $this->request->request('postcode','');
        $is_true = 1;
        if($postcode){
            $a = str_replace(" ", "", $postcode);
            if(strlen($a) >= 4 && strlen($a) <= 8){
                if(is_numeric($a[0])) $is_true = 0;;
                if(is_numeric($a[strlen($a)-1])) $is_true = 0;;

                if(strlen($a) == 4){
                    if(is_english($a[1])) $is_true = 0;;
                    if(is_english($a[2])) $is_true = 0;;
                }elseif(strlen($a) == 5){
                    //第一个和最后一个肯定是
                    if(is_english($a[2])) $is_true = 0;;
                }elseif(strlen($a) == 6){
                    if(is_english($a[2])) $is_true = 0;;
                    if(is_english($a[3])) $is_true = 0;;
                }elseif(strlen($a) == 7){
                    if(is_english($a[2])) $is_true = 0;;
                    if(is_english($a[3])) $is_true = 0;;
                    if(is_english($a[4])) $is_true = 0;;
                }elseif(strlen($a) == 8){
                    if(is_numeric($a[1])) $is_true = 0;;
                    if(is_english($a[2])) $is_true = 0;;
                    if(is_english($a[3])) $is_true = 0;;
                    if(is_english($a[4])) $is_true = 0;;
                    if(is_english($a[5])) $is_true = 0;;
                    if(is_numeric($a[6])) $is_true = 0;;
                }
            }else{
                $is_true = 0;;
            }
        }

        if($is_true){
            $data = array(
                "postcode"  => $postcode,
                "key"       => "b4d0a-5a741-c173d-0959c",
                "response"  => "data_formatted"
            );
            $data_string = json_encode($data);
            $ch = curl_init('http://pcls1.craftyclicks.co.uk/json/rapidaddress');
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
            );
            $result = curl_exec($ch);
            $data = json_decode($result,true);
            if(!empty($data['error_code'])){
                $this->error($data['error_msg']);
            }else{
                
                $delivery_points = $data['delivery_points'];
                $line_1_arr = [];
                $line_2_arr = [];
                foreach ($delivery_points as $v) {
                    if(!empty($v['line_1']) &&  !in_array($v['line_1'],$line_1_arr)){
                        $line_1_arr[] = $v['line_1'];
                        $line_2_arr[] = $v['line_2'];
                    }
                }
                $this->success('操作成功',['data'=>$data,'line_1_arr'=>$line_1_arr,'line_2_arr'=>$line_2_arr]);
            }
        }
    }


    //获取总未读消息数量
    public function get_user_message_count(){
        $user_id=$this->request->request('user_id',0);
		$where1 = ['js_user_id'=>$user_id,'status'=>1,'is_read'=>0];
		$is_read_count = ChatMessage::where($where1)->count();
		$GroupChatUser = GroupChatUser::where(['user_id'=>$user_id])->find();
        if($GroupChatUser){
            $is_read_count = $is_read_count + $GroupChatUser['unread_num'];
        }
		if($is_read_count > 99){
			$is_read_count  = 99;
		}
        $this->success('操作成功',$is_read_count);
    }
    //群操作
    public function finish_board(){
        $group_chat_id = $this->request->request('group_chat_id');
        $group_name = $this->request->request('group_name','');
        $type = $this->request->request('type',0); // 0是已读操作  1是修改群昵称  2是修改群聊名称  3是修改群公告  4退出群聊
        if(!$group_chat_id){
            $this->error('操作失败');
        }
        if($type == 0){
            $update = ['is_content'=>1];
            GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->update($update);
        }elseif($type == 1){
            $update = ['group_name'=>$group_name];
            GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->update($update);
        }elseif($type == 2){
            $update = ['name'=>$group_name];
            GroupChat::where(['id'=>$group_chat_id])->update($update);
        }elseif($type == 3){ 
            $update = ['content'=>$group_name];
            GroupChat::where(['id'=>$group_chat_id])->update($update);
            GroupChatUser::where(['group_chat_id'=>$group_chat_id])->update(['is_content'=>0]);
        }elseif($type == 4){ 
            $update = ['status'=>-1];
            GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->update($update);
        }
        $this->success('操作成功');
    }
    
    //获取消息列表
    public function get_user_message(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $where = [
            'status'=>1,
            'user_id'=>$this->user['id'],
            'is_group_chat'=>0
        ];
        $where1 = [
            'status'=>1,
            'js_user_id'=>$this->user['id'],
            'is_group_chat'=>0
        ];

        $subQuery = ChatMessage::where($where)
        ->whereOr(function($query) use ($where1){
            $query->where($where1);
        })->field('max(add_time) as add_time')->group('sort')->buildSql();

        if($this->user['id'] == 439){
            $where['a.is_system_chat'] = 0;
            $where1['a.is_system_chat'] = 0;
            $list = ChatMessage::alias('a')
            ->field("a.*")
            ->where($where)
            ->whereOr(function($query) use ($where1){
                $query->where($where1);
            })
            ->group('sort')
            ->order('add_time desc')
            ->join("$subQuery b","b.add_time = a.add_time") // 关键点
            ->limit(($page-1)*$pagesize,$pagesize)
            ->select();
          
        }else{
            $list = ChatMessage::alias('a')
            ->field("a.*")
            ->where($where)
            ->whereOr(function($query) use ($where1){
                $query->where($where1);
            })
            ->group('sort')
            ->order('add_time desc')
            ->join("$subQuery b","b.add_time = a.add_time") // 关键点
            ->limit(($page-1)*$pagesize,$pagesize)
            ->select();
        }

        //获取消息列表
        // $list = ChatMessage::where($where)
        // ->whereOr(function($query) use ($where1){
        //     $query->where($where1);
        // })->group('sort')->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
        $arr = [];
        if($list){
            foreach ($list as $k=>&$info) {
                //$info =  ChatMessage::where(['status'=>1,'sort'=>$v['sort']])->order('add_time desc')->find();
                if($info['user_id'] == $this->user['id']){
                    $where = ['id'=>$info['js_user_id']];
                }else{
                    $where = ['id'=>$info['user_id']];
                }
                $info['user'] = UserModel::where($where)->find();
                $info['add_time'] = date('m-d H:i:s',$info['add_time']);
                //查询未读消息数量
                $info['wd'] = ChatMessage::where(['status'=>1,'sort'=>$info['sort'],'is_read'=>0,'js_user_id'=>$this->user['id']])->count();
                $info['img'] = '';
                $info['shop_user_id'] = 0;
                //查询图片
                if($info['product_id']){
                    $res = Product::where(['id'=>$info['product_id']])->find();
                    $info['img'] = $res['video_img'];
                    $info['shop_user_id'] = $res['user_id'];
                }elseif($info['wish_id']){
                    $res = ProductWish::where(['id'=>$info['wish_id']])->find();
                    $info['img'] = $res['video_img'];
                    $info['shop_user_id'] = $res['user_id'];
                }
                //$arr[] = $info;
            }

            //$sort = array_column($arr,'add_time');
            //array_multisort($sort,SORT_DESC,$arr);
        }
        $message['list'] = $list;
        $message['sys']=ProductMessage::field('title,add_time')->where(array('type'=>3,'to_user_id'=>$this->user['id']))->order('add_time desc')->limit(0,1)->find();
		if($message['sys']){
			$message['sys']['add_time']=date("Y-m-d H:i:s",$message['sys']['add_time']);
		}else{
		    $message['sys']="";
		}
		$message['sys_unread']=ProductMessage::where(array('type'=>3,'to_user_id'=>$this->user['id'],'is_read'=>0))->count();
        //查询群聊
        $where = [
            'status'=>1  
        ];
        $res = GroupChat::where($where)->select();
        $arr = [];
        if($res){
            foreach ($res as $v) {
                $d = GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$v['id'],'status'=>1])->find();
                if($d){
                    $v['is_content'] = $d['is_content'];
                    $v['unread_num'] = $d['unread_num'];
                    $arr[] = $v;
                }
                $v['content_text'] = ChatMessage::where(['sort'=>$v['identification'],'type'=>1])->order('id desc')->value('content');
            }
        }
        $message['groupChatList'] = $arr;
        $this->success('获取成功',$message);
    }

    //撤回聊天记录
    public function delete_chat_message(){
        $id = $this->request->request('id');
        $res = ChatMessage::where(['id'=>$id])->update(['status'=>-1]);
        if($res){
            $this->success('撤回成功');
        }else{
            $this->error('撤回失败');
        }
    }
    //群聊移除用户
    public function delete_chat_message_user(){
        $user_id = $this->request->request('user_id');
        $res = GroupChatUser::where(['user_id'=>$user_id])->delete();
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    
    //获取群用户人数
    public function groupChatUserList(){
        $group_chat_id = $this->request->request('group_chat_id',0);
        $page=$this->request->request('page',1);
		$pagesize= $this->request->request('pagesize',20);
        $where = [
            'a.group_chat_id'=>$group_chat_id,
            'a.status'=>1
        ];
        $list = GroupChatUser::alias('a')
        ->field("b.avatar,b.nickname,a.user_id")
        ->where($where)
        ->order('grade asc')
        ->join("user b","b.id = a.user_id") // 关键点
        ->limit(($page-1)*$pagesize,$pagesize)
        ->select();
        $group_name = GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->value('group_name');
        if(!$group_name){
            $group_name = $this->user['nickname'];
        }
        $this->success('获取成功',['list'=>$list,'group_name'=>$group_name]);
    }

    //获取聊天内容
    public function getmessageList(){
        $product_id = $this->request->request('id',0);
        $wish_id = $this->request->request('wish_id',0);
        $sort = $this->request->request('sort','');
        $js_user_id = $this->request->request('js_user_id',0);
        $is_group_chat = $this->request->request('is_group_chat',0);
        $group_chat_id = $this->request->request('group_chat_id',0);
        $page=$this->request->request('page',1);
		$pagesize= $this->request->request('pagesize',20);
        
        if(!$sort){
            $where = [
                'status'=>1,
                'user_id'=>$this->user['id'],
                'product_id'=>$product_id,
                'wish_id'=>$wish_id,
                'js_user_id'=>$js_user_id,
                'is_group_chat'=>$is_group_chat
            ];
            $where1 = [
                'status'=>1,
                'user_id'=>$js_user_id,
                'product_id'=>$product_id,
                'wish_id'=>$wish_id,
                'js_user_id'=>$this->user['id'],
                'is_group_chat'=>$is_group_chat
            ];
            $list = ChatMessage::where($where)
            ->whereOr(function($query) use ($where1){
                $query->where($where1);
            })->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();

            if(!$list && $product_id){
                //未查询到聊天数据则相当于第一次则发送一条消息过去
                $data = [
                    'add_time'=>time(),
                    'product_id'=>$product_id,
                    'content'=>'你好，你的闲置我想要，请问还在吗?',
                    'wish_id'=>$wish_id,
                    'type'=>1,
                    'sort'=>$js_user_id.$wish_id.$product_id.$this->user['id'],
                    'add_time'=>time(),
                    'user_id'=>$this->user['id'],
                    'js_user_id'=>$js_user_id
                ];
                ChatMessage::insert($data);

                $list = ChatMessage::where($where)
                ->whereOr(function($query) use ($where1){
                    $query->where($where1);
                })->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
                
                //查看该用户是否是今天收到的第一条私信  是的话短信推送
                $count = ChatMessage::whereTime('add_time', 'today')->where(['js_user_id'=>$data['js_user_id']])->count();
                if($count == 1){
                    $mobile = UserModel::where(['id'=>$data['js_user_id']])->value('mobile');
                    send_mobile($mobile,'SMS_471950193');
                }
            }
        }else{
            //查询该用户入群时间
            $where = [
                'status'=>1,
                'sort'=>$sort,
                'is_group_chat'=>$is_group_chat
            ];
            if($is_group_chat){
                //$add_time = GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->value('add_time');
                //$where['add_time'] = ['>',$add_time];
            }
            $list = ChatMessage::where($where)->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
        }

        if($is_group_chat){
            GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->update(['unread_num'=>0]);
        }

        $ids = [];
        $arrPX1 = [];
        if($list){
            //执行排序
            if($page == 1){
                foreach ($list as $k=>&$v) {
                    $arrPX1[$k] =  $v['id'];
                }
                array_multisort($arrPX1, SORT_ASC, $list);
            }
            $avatar = UserModel::where(['id'=>$this->user['id']])->value('avatar');
            $last_time = 0;
            foreach ($list as $k=>&$v) {
                $v['cunzai'] = 0;
                if($v['user_id'] != $this->user['id']){
                    $list[0]['cunzai'] = 1;
                }
                if($v['is_group_chat'] == 1){ //群聊消息
                    $where = ['id'=>$v['user_id']];
                }else{
                    //查看用户信息
                    if($v['user_id'] == $this->user['id']){
                        //他发给我的
                        $where = ['id'=>$v['js_user_id']];
                        if($v['user_id'] == $v['js_user_id']){
                            $ids[] = $v['id'];
                        }
                    }else{
                        //我发给他的
                        if($v['is_read'] == 0){
                            //如果有未读消息则更新为已读
                            $ids[] = $v['id'];
                        }
                        $where = ['id'=>$v['user_id']];
                    }
                }
                $v['avatar'] = $avatar;
                $v['user'] = UserModel::field('id,nickname,avatar,mobile')->where($where)->find();
                if(!$v['user']){
                    unset($list[$k]);
                    continue;
                }
                $group_name = GroupChatUser::where(['user_id'=>$v['user_id'],'group_chat_id'=>$group_chat_id])->value('group_name');
                if($group_name){
                    $v['user']['nickname'] = $group_name;
                }
                $v['time'] = '';
                if(!$last_time){
                    $v['time'] =  date('m-d H:i',$v['add_time']);
                    $last_time = $v['add_time'];
                }elseif(($v['add_time'] - $last_time) > 7600){
                    $v['time'] =  date('m-d H:i',$v['add_time']);
                    $last_time = $v['add_time'];
                }
                $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
                $v['len'] = 0;
                if($v['type'] == 1){ //文字
                    //判断发布文字有多少个字
                    $len = mb_strlen($v['content'], 'UTF-8');
                    $v['len'] = 135;
                    if($len > 16 && $len <= 32){
                        $v['len'] = 170;
                    }elseif($len > 32 && $len <= 48){
                        $v['len'] = 210;
                    }elseif($len > 48 && $len <= 64){
                        $v['len'] = 250;
                    }elseif($len > 64 && $len <= 80){
                        $v['len'] = 290;
                    }elseif($len > 80 && $len <= 96){
                        $v['len'] = 330;
                    }elseif($len > 96 && $len <= 122){
                        $v['len'] = 370;
                    }elseif($len > 122 && $len <= 138){
                        $v['len'] = 410;
                    }elseif($len > 138){
                        $v['len'] = 450;
                    }
                }elseif($v['type'] == 2){ //图片
                    $v['len'] = 290;
                }elseif($v['type'] == 3){ //商品
                    $v['len'] = 270;
                    $v['product'] = Product::field('id,video_img,title,price')->where(['id'=>$v['goods_id']])->find();
                }
                if($v['time']){
                    $v['len'] = $v['len'] + 40;
                }
            }
        }
        $list = array_values($list);
        if($ids){
            ChatMessage::where(['id'=>['in',$ids]])->update(['is_read'=>1]);
        }
        
        $this->success('操作成功',$list);
    }
    //获取我的群昵称
    public function get_group_name(){
        $group_chat_id = $this->request->request('group_chat_id',0);
        $group_name = GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->value('group_name');
        $count = GroupChatUser::where(['group_chat_id'=>$group_chat_id])->count();
        if($group_name){
            $this->success('获取成功',['group_name'=>$group_name,'count'=>$count]);
        }else{
            $this->success('获取成功',['group_name'=>$this->user['nickname'],'count'=>$count]);
        }

    }

    
    //新增聊天内容
    public function add_report(){
        $product_id = $this->request->request('id',0);
        $wish_id = $this->request->request('wish_id',0);
        $sort = $this->request->request('sort','');
        $js_user_id = $this->request->request('js_user_id',0);
        $titleReport = $this->request->request('titleReport','');
        $img = $this->request->request('img','');
        $type = $this->request->request('type',1);
        $goods_id = $this->request->request('goods_id',0);
        $is_group_chat = $this->request->request('is_group_chat',0);
        if(!trim($titleReport) && !$img && $goods_id == 0){
            $this->error('聊天内容不能为空');
        }
        if($this->user['is_chat_message'] == 1){
            $this->error('您已被禁言,无法发送聊天消息');
        }

       

        $data = [
            'add_time'=>time(),
            'product_id'=>$product_id,
            'content'=>trim($titleReport),
            'wish_id'=>$wish_id,
            'img'=>$img,
            'type'=>$type ? $type : 1,
            'goods_id'=>$goods_id,
            'is_group_chat'=>$is_group_chat
        ];
        //群聊消息
        if($is_group_chat){
            $data['user_id'] = $this->user['id'];
          
        }else{ //私聊消息
            if(!$sort){
                //查询上一条消息
                $where = [
                    'product_id'=>$product_id,
                    'wish_id'=>$wish_id,
                    'status'=>1,
                    'user_id'=>$this->user['id'],
                    'js_user_id'=>$js_user_id,
                ];
                $where1 = [
                    'product_id'=>$product_id,
                    'wish_id'=>$wish_id,
                    'status'=>1,
                    'user_id'=>$js_user_id,
                    'js_user_id'=>$this->user['id'],
                ];
                //获取消息列表
                $info = ChatMessage::where($where)->whereOr(function($query) use ($where1){
                    $query->where($where1);
                })->order('add_time desc')->find();
                if(!$info){
                    $sort = $js_user_id.$wish_id.$product_id.$this->user['id'];
                    if($js_user_id == $this->user['id']){
                        $this->error('不能给自己发消息');
                    }
                }else{
                    $sort = $info['sort'];
                }
                
            }
            $info = ChatMessage::where(['sort'=>$sort])->find();
            
            if($info){
                if($this->user['id'] == $info['user_id'] ){
                    $data['user_id'] = $info['user_id'];
                    $data['js_user_id'] = $info['js_user_id'];
                }else{
                    $data['user_id'] = $info['js_user_id'];
                    $data['js_user_id'] = $info['user_id'];
                }
            }else{
                $data['user_id'] = $this->user['id'];
                $data['js_user_id'] = $js_user_id;
            }
        }
        $data['sort'] = $sort;
        
        $where = [
            'product_id'=>$data['product_id'],
            'wish_id'=>$data['wish_id'],
            'type'=>$data['type'],
            'goods_id'=>$data['goods_id'],
            'user_id'=>$data['user_id'],
            'sort'=>$data['sort'],
        ];
        if(!empty($data['js_user_id'])){
            $where['js_user_id'] = $data['js_user_id'];
        }
        $add_time = ChatMessage::where($where)->order('add_time desc')->value('add_time');
        if($add_time == $data['add_time']){
            $this->success('请勿重复发送');
        }

        $id = ChatMessage::insertGetId($data);
        //发送成功给接受者发送推送消息
        $geTui = new GeTui();
        if(!$is_group_chat){
            //添加成功执行推送逻辑
            $cid = UserModel::where(['id'=>['in',$data['js_user_id']]])->value('cid');
            if($cid){
                $geTui->pushToSingleByCid($cid,'消息提醒','你有一条新的消息,请注意查收','/pages/message/message');
            }

            //查看该用户是否是今天收到的第一条私信  是的话短信推送
            $count = ChatMessage::whereTime('add_time', 'today')->where(['js_user_id'=>$data['js_user_id']])->count();
            if($count == 1){
                $mobile = UserModel::where(['id'=>$data['js_user_id']])->value('mobile');
                send_mobile($mobile,'SMS_471950193');
            }
            
        }else{
            $redis = redis_init();
            $name = 'group_chat_user_sum'.$sort;
            $info = $redis->get($name);
            if($info){
                $redis->set($name,$info+1);
            }else{
                $redis->set($name,1);
            }
        }
        
        $this->success('发送成功',$id);
    }

    //我的邀请
	public function my_invite(){
		$type= $this->request->request('type',1);
        if($type == 1){ //查询我的邀请详情
            $page= $this->request->request('page',1);
            $pagesize= $this->request->request('pagesize',10);
            $where = [
                'invite_user_id'=>$this->user['id']
            ];
            $month_log = UserModel::field('id,nickname,avatar,add_time')->where($where)->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
            foreach($month_log as $a=>&$v){
                $v['add_time']=date("Y-m-d",$v['add_time']);
                //查询该用户是否发过商品
                $res = Product::where(['user_id'=>$v['id'],'status'=>1,'is_del'=>0])->find();
                $v['is_yx'] = $res ? 1 : 0;
            }
        }else{
            $where = [
                'invite_user_id'=>$this->user['id']
            ];
            $month_log = UserModel::field('id,nickname,avatar,add_time')->where($where)->order('add_time desc')->select();
            $num = 0; //有效用户
            foreach($month_log as &$v){
                //查询该用户是否发过商品
                $res = Product::where(['user_id'=>$v['id'],'status'=>1,'is_del'=>0])->find();
                if($res){
                    $num += 1;
                }
            }
            $month_log = [
                'sum'=>count($month_log),
                'num'=>$num,
                'score'=>count($month_log) * 10
            ];
        }
		
        $this->success('发送成功',$month_log);
	}


    



    
    //获取用户信息
    public function getUser(){
        $user = UserModel::where('id',$this->user['id'])->find();
        if($user){
            $where = [];
            $where['status']=1;
            $where['is_sale']=0;
            $where['price']=['elt',$user['rose_money']];
            $goods_num =Product::where($where)->count();
            //判断该用户是否是商家
            $info = Shop::where(['user_id'=>$user['id'],'status'=>1])->find();
            $user['is_shop'] = $info?1:0;

            //查询该用户是否存在过期商品  存在则更新
            $where = [
                'status'=>1,
                'is_sale'=>0,
                'day'=> ['<',(time()-(30*24*3600))],
                'is_in'=>1,
                'user_id'=>$user['id']
            ];
            $res = Product::where($where)->limit(0,5)->order('day asc')->select();
            $is_in_product_height = 0;
            if($res){
                foreach ($res as $a=>&$b) {
                    if(!$v['video_img']){
                        $v['video_img']=$v['imgsa'][0];
                    }
                    if(strstr($v['video_img'], 'mp4')){
                        $v['video_img'] = $v['video_img'].'?x-oss-process=video/snapshot,t_1000,m_fast,ar_auto';
                    }
                    $ress= explode('oa.yuxiang123.cn/',$v['video_img']);
                    if (!empty($ress[1]) &&  !file_exists($ress[1])) {
                        Product::where(['id'=>$v['id']])->update(['status'=>-1]);
                        unset($res[$a]);
                    } 
                }
                $res = array_values($res);
                if(count($res) == 1){
                    $is_in_product_height = '38%';
                }elseif(count($res) == 2){
                    $is_in_product_height = '33%';
                }elseif(count($res) == 3){
                    $is_in_product_height = '27%';
                }elseif(count($res) == 4){
                    $is_in_product_height = '22%';
                }elseif(count($res) == 5){
                    $is_in_product_height = '16%';
                }
            }
            $this->success('获取成功',['user'=>$user,'goods_num'=>$goods_num,'is_in_product'=>$res,'is_in_product_height'=>$is_in_product_height]);
        }
    }

    //更新用户cid
    public function set_is_in(){
        $product_id = $this->request->request('product_id','');
        $status = $this->request->request('status','');

        $info = Product::where(['id'=>$product_id,'is_in'=>1,'user_id'=>$this->user['id']])->find();
        if(!$info){
            $this->error('参数错误,操作失败');
        }
        if($status == -1){  //下架
            Product::where(['id'=>$product_id])->update(['status'=>-1]);
        }elseif($status == 1){  //在售
            Product::where(['id'=>$product_id])->update(['is_in'=>0,'add_time'=>time(),'day'=>time()]);
        }
        $this->success('操作成功');
    }

    



    //更新用户cid
    public function updateCid(){
        $cid = $this->request->request('cid','');
        if($cid){
            UserModel::where('id',$this->user['id'])->update(['cid'=>$cid]);
        }
        $this->success('操作成功');
    }

    //删除评论
    public function del_comment(){
		$id=$this->request->request('id',0);
		if($id){
            $where = [
                'id'=>$id,
                'user_id'=>$this->user['id'],
                'type'=>0
            ];
			$ProductMessage=ProductMessage::where($where)->find();
			if(!$ProductMessage){
				$this->error('操作失败');
			}
            ProductMessage::where($where)->delete();
            $this->success('删除成功');
		}else{
			$this->error('缺少参数');
		}	
	}

    //个人主页-接口
	public function homepage(){
		$user_id=$this->request->request('user_id');
		$user=UserModel::where(array('id'=>$user_id))->find();
        $user['rose_in']=UserRoseLog::where(['user_id'=>$user_id,'rose_money'=>array('gt',0),'type'=>['neq',18]])->sum('rose_money');
        if($user['is_shop'] == 0){
            $user['rose_level']=rose_level($user['rose_in']);
        }
        $user['level_name']=level_name($user['rose_in']);
        //余享号
		$user['yxh']=$user['id']+10000;
		$user['sdk_version']='1.3.4';
        $user['user_mp'] = MpMp::where(['user_id'=>$user_id,'status'=>1])->order('add_time desc')->find();
        //生成名片二维码
        if($user['user_mp']){
            if(!$user['mp_code']){
                $user['mp_code'] = $this->getMpQrcode($user['user_mp']['id']);
                UserModel::where(array('id'=>$user_id))->update(['mp_code'=>$user['mp_code']]);
            }
        }
        $mp_ids = MpMp::where(['user_id'=>$user_id,'status'=>1])->column('id');

        //点击数量
		$user['click_num'] = MpClick::where(['mp_id'=>['in',$mp_ids],'type'=>1])->count();
		$user['phone_click_num'] = MpClick::where(['mp_id'=>['in',$mp_ids],'type'=>2])->count();
		$user['day_click_num'] = MpClick::whereTime('add_time', 'today')->where(['mp_id'=>['in',$mp_ids],'type'=>1])->count();

        $this->success('获取用户信息',['user'=>$user]);
	}

    //获取名片二维码
    public function getMpQrcode($mp_id){
        $appid = 'wx84f56a63b9f63e03';
        $secret = '98b698d6f873fdd2292684babd69c975';
        $res= file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
        $tokens=json_decode($res,true);
        if(empty($tokens['access_token'])){
            $curl = curl_init("https://api.weixin.qq.com/cgi-bin/stable_token");
            $parameters = json_encode(["grant_type"=>"client_credential", "appid"=>$appid,'secret'=>$secret]);
            $header = ['Content-type:application/json', 'Accept-Charset:UTF-8'];
            $options = [
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => $header,
                CURLOPT_POSTFIELDS => $parameters,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 60,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_SSL_VERIFYHOST => 2
            ];
            curl_setopt_array($curl, $options);
            $tokens = json_decode(curl_exec($curl),true);
            curl_close($curl);
        }
        $access_token=$tokens['access_token'];
        $url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        //$data=array('page'=>'pages/shop/shopClass','scene'=>$this->user['id'],'width'=>120);
        $data=array('page'=>'subone/index/user_gr','scene'=>$mp_id,'width'=>120);
        $res = httpRequest($url, $data, "json");
        //二维码图片地址	
        $qr_code ='uploads/invite/'.time().rand(1000, 9999).'.png';
        file_put_contents($qr_code ,$res);
        return $qr_code;
    }


    //获取状态
    public function getStatusTask(){
        $autocity = $this->request->request('autocity','');
        $data = [
            'task0'=>0,
            'task1'=>0,
            'task2'=>0,
            'task3'=>0,
            'task4'=>0,
            'task5'=>0,
            'task6'=>0,
            'task7'=>0,
            'task9'=>0,
            'task10'=>0,
        ];
        
        $rose_money = 0;
        if($this->user){ //登录了
            $rose_money = $this->user['rose_money'];

            // if($autocity == '孝感市'){  //宝忠
            //     $time =  strtotime(date('Y-m-d',time()));
            //     $info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>1,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
            //     if($info){
            //         $data['task1'] = $info['status'] == 0 ? 1 : 2;
            //     }
            //     $info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>2,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
            //     if($info){
            //         $data['task2'] = $info['status'] == 0 ? 1 : 2;
            //     }
            //     $info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>3,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
            //     if($info){
            //         $data['task3'] = $info['status'] == 0 ? 1 : 2;
            //     }
            //     // $info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>4,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
            //     // if($info){
            //     //     $data['task4'] = $info['status'] == 0 ? 1 : 2;
            //     // }
            // }else{
            $data = [];
            $redis = redis_init();
            //看广告
            $name = 'add_score_26_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task0'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task0'] = 1; 
                }
            }

            //每日分享小程序到微信/社群
            $name = 'add_score_21_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task1'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task1'] = 1; 
                }
            }
            //每日成功发布一个闲置
            $info = $redis->get($this->user['id'].'roseandlog');	
            if(!$info){
                $data['task2'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task2'] = 1; 
                }
            }

            //每日成功发布一个心愿
            $info = $redis->get($this->user['id'].'ProductWish');	
            if(!$info){
                $data['task3'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task3'] = 1; 
                }
            }
            
            //每日分享我的闲置到微信/社群
            // $name = 'add_score_24_'.$this->user['id'];
            // $info = $redis->get($name);
            // if(!$info){
            //     $data['task4'] = 1; 
            // }else{
            //     //判断发布时间
            //     $time1 = date('Y-m-d',$info);
            //     $time2 = date('Y-m-d',time());
            //     if($time1 != $time2){
            //         $data['task4'] = 1; 
            //     }
            // }

            //每日发布一条动态
            $name = $this->user['id'].'CommunityModel';
            $info = $redis->get($name);
            if(!$info){
                $data['task4'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task4'] = 1; 
                }
            }

            //关注公众号奖励
            $name = 'add_score_22_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task5'] = 1; 
            }

            //添加官方小助手
            $name = 'add_score_23_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task6'] = 1; 
            }
            //首次订单完成
            $name = 'add_score_25_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task7'] = 1; 
            }
            
            //每日签到
            $name = 'add_score_27_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task9'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task9'] = 1; 
                }
            }
            //更新头像和昵称   
            $name = 'add_score_28_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task10'] = 1; 
            }
        }
        $this->success('获取成功',['data'=>$data,'rose_money'=>$rose_money]);
    }

    //管理员冻结用户
    public function admin_freeze_user(){
        $user_id = $this->request->request('user_id','');
        if($this->user['is_admin'] != 1){
            $this->error('没有权限操作!');
        }
        Db::startTrans();
		try {
            if($user_id){
                $res = UserModel::where('id',$user_id)->update(['status'=>0]);
                if($res){
                    //该用户所有上架的信息全部下架
                    Product::where(['user_id'=>$user_id])->update(['status'=>-1]);
                    ProductWish::where(['user_id'=>$user_id])->update(['status'=>-1]);
                    Community::where(['user_id'=>$user_id])->update(['status'=>-1]);
                    Db::commit();
                    $this->success('冻结成功');
                }else{
                    Db::commit();
                    $this->error('冻结失败');
                }
            }else{  
                Db::commit();
                $this->error('冻结失败');
            }
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
    }

    //管理员下架动态/心愿/闲置
    public function admin_xj(){
        $id = $this->request->request('id','');
        $type = $this->request->request('type','1');
        if($this->user['is_admin'] != 1){
            $this->error('没有权限操作!');
        }
        if($id){
            if($type == 1){ //闲置
                $res = Product::where('id',$id)->update(['status'=>-1]);
            }elseif($type == 2){  //心愿
                $res = ProductWish::where('id',$id)->update(['status'=>-1]);
            }elseif($type == 3){  //动态
                $res = Community::where('id',$id)->update(['status'=>-1]);
            }elseif($type == 4){  //加入公众号内容选择
                $res = Product::where('id',$id)->update(['is_gzh_select'=>1]);
            }
            if($res){
                $this->success('下架成功');
            }else{
                $this->error('下架失败');
            }
        }else{
            $this->error('下架失败');
        }
    }

    //更新个人资料
	public function profile_save(){
        $data = [];
        $this->request->request('nickname','') ? $data['nickname'] = $this->request->request('nickname','') : '' ; 
        $this->request->request('avatar','') ? $data['avatar'] =  $this->request->request('avatar','') : '' ;
        $this->request->request('profile','') ? $data['profile'] =  $this->request->request('profile','') : '' ;
        $this->request->request('gender','') ? $data['gender'] =  $this->request->request('gender','') : '' ;
        $this->request->request('birthday','') ? $data['birthday'] =  $this->request->request('birthday','') : '' ;
        $this->request->request('city','') ? $data['city'] =  $this->request->request('city','') : '' ;
        $this->request->request('bgimg','') ? $data['bgimg'] =  $this->request->request('bgimg','') : '' ;
        $this->request->request('tags','') ? $data['tags'] =  $this->request->request('tags','') : '' ;
        $this->request->request('identityid','') ? $data['identityid'] =  $this->request->request('identityid','') : '' ;
        $this->request->request('weixin','') ? $data['weixin'] =  $this->request->request('weixin','') : '' ;
        $mobile = $this->request->request('mobile','');
        $phone = $this->request->request('phone','');
        $is_login = $this->request->request('is_login','');
        if($is_login && (!$phone && !$this->user['mobile'])){
            $this->error('请输入手机号');
        }
        if($phone){
            if(!check_phone($phone)){
                $this->error('手机号码无效');
            }
            $info = UserModel::where(['mobile'=>$phone,'status'=>1,'is_shop'=>0])->find();
            if($info){
                $this->error('该手机号已存在用户,请重新输入');
            }

            $data['mobile'] = $phone;
            UserModel::where(['id'=>$this->user['id']])->update($data);
            $this->success('操作成功');
        }
		if(!empty($mobile) && $mobile!=$this->user['mobile']){
		    $code=$this->request->request('code','');
		    if(empty($code)){
                $this->error('请输入验证码');
		    }
		    $mobile_code=MobileCode::where(array('mobile'=>$mobile,'verify'=>0))->order('add_time desc')->limit(0,1)->find();
			if($code!=$mobile_code['code']){
                $this->error('验证码错误');
			}
			if(check_phone($mobile)){
			    $data['mobile']=$mobile;
			}else{
                $this->error('新手机号码无效');
			}
		}
		if(!empty($data)){
           
			UserModel::where(array('id'=>$this->user['id']))->update($data);
            $name = 'add_score_28_'.$this->user['id']; 
            $name1 = 'add_score_28_avatar_'.$this->user['id']; //头像
            $name2 = 'add_score_28_nickname_'.$this->user['id']; //昵称
            $name3 = 'add_score_28_gender_'.$this->user['id']; //性别
            $name4 = 'add_score_28_birthday_'.$this->user['id'];  //生日
            $name5 = 'add_score_28_city_'.$this->user['id']; //地区
            $redis = redis_init();
            if(!$redis->get($name)){
                if(!empty($data['avatar'])){
                    if($redis->get($name2) && $redis->get($name3) && $redis->get($name4) && $redis->get($name5) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name1,1);
                    }
                }
                if(!empty($data['nickname'])){
                    if($redis->get($name1) && $redis->get($name3) && $redis->get($name4) && $redis->get($name5) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name2,1);
                    }
                }
                if(!empty($data['gender'])){
                    if($redis->get($name1) && $redis->get($name2) && $redis->get($name4) && $redis->get($name5) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name3,1);
                    }
                }
                if(!empty($data['birthday'])){
                    if($redis->get($name1) && $redis->get($name2) && $redis->get($name3) && $redis->get($name5) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name4,1);
                    }
                }
                if(!empty($data['city'])){
                    if($redis->get($name1) && $redis->get($name2) && $redis->get($name3) && $redis->get($name4) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name5,1);
                    }
                }
            }
            $this->success('修改成功');
		}else{
            $this->error('请输入修改内容');
		}
	}

    //给用户添加积分
    public function add_score(){
        $type = $this->request->post('type');
        $score = $this->request->post('score');

        $redis = redis_init();

        if($type == 21){  //分享好友奖励
            $name = 'add_score_21_'.$this->user['id'];
            $title = '每日分享小程序到微信/社群';
        }elseif($type == 22){  //关注公众号奖励
            $name = 'add_score_22_'.$this->user['id'];
            $title = '关注公众号奖励';
        }elseif($type == 23){  //加小助手微信号奖励
            $name = 'add_score_23_'.$this->user['id'];
            $title = '加小助手微信号奖励';
        }elseif($type == 24){  //分享闲置商品奖励
            $name = 'add_score_24_'.$this->user['id'];
            $title = '每日分享闲置商品';
        }elseif($type == 26){  //广告
            $name = 'add_score_26_'.$this->user['id'];
            $title = '广告奖励';
        }elseif($type == 27){  //签到
            $name = 'add_score_27_'.$this->user['id'];
            $title = '签到奖励';
            $day = $redis->get($name.'time');
            if(!$day){
                //1积分
                $redis->set($name.'time',strtotime(date("Y-m-d 23:59:59")));
            }else{
                if((time() - $day) < 3600*24){  //连续签到 积分+2
                    $score = 2;
                }
                $redis->set($name.'time',strtotime(date("Y-m-d 23:59:59")));
            }

        }elseif($type == 30){  //分享抽奖得积分
            $name = 'add_score_30_'.$this->user['id'];
            $title = '分享抽奖得积分';
        }
       
        $info = $redis->get($name);
        if(!$info){
            //未获取过奖励则直接给奖励
            roseandlog($this->user['id'],$score,$type,$title);
            $redis->set($name,time());
            $this->success('给奖励成功',$score);
        }else{
            if($type == 21 || $type == 24 || $type == 26 || $type == 27  || $type == 30){
                //判断发布时间
				$time1 = date('Y-m-d',$info);
				$time2 = date('Y-m-d',time());
				if($time1 != $time2){
					//上次发布不是今天 给奖励
					roseandlog($this->user['id'],$score,$type,$title);
					$redis->set($name,time());
                    $this->success('给奖励成功',$score);
				}
            }
        }

        $this->error('今日奖励已获取');
    }
    //账号注销
	public function account_cancel(){
		$mobile=$this->request->request('mobile','');
		$code=$this->request->request('code','');
		if(empty($mobile)){
            $this->error('请输入手机号');
		}
		if(empty($code)){
            $this->error('请输入验证码');
		}
		$mobile_code=MobileCode::where(array('mobile'=>$mobile,'verify'=>0))->order('add_time desc')->limit(0,1)->find();
		if($code!=$mobile_code['code']){
            $this->error('验证码错误');
		}
        //查询该用户是否存在闲置商品
        $info = Product::where(['user_id'=>$this->user['id'],'is_sale'=>0,'status'=>1])->find();
        if($info){
            $this->error('您还有想要送出的闲置,如需注销请先下架闲置商品后进行注销');
        }
		UserModel::where(array('id'=>$this->user['id']))->update(array('mobile'=>$this->user['mobile'].'_2','status'=>-1));
        $this->success('注销成功');
	}


    //我的浏览记录 / 我的收藏
	public function user_product_view(){
		$page=$this->request->request('page',1);
		$pagesize=$this->request->request('pagesize',18);
		$type=$this->request->request('type',1); // 默认是1 我的浏览记录   2我的收藏
        if($type == 1){
            $list=ProductViewLog::where(array('user_id'=>$this->user['id'],'product_id'=>array('gt',0)))->order('add_time desc')->limit($page*$pagesize-$pagesize,$pagesize)->select();
        }else{
            $list=UserCollect::where(array('user_id'=>$this->user['id'],'product_id'=>array('gt',0)))->order('add_time desc')->limit($page*$pagesize-$pagesize,$pagesize)->select();
        }
		if($list){
	    	foreach($list as $a=>&$b){
        		$v['product']=Product::where(array('id'=>$v['product_id'],'status'=>1))->find();
        		if(!$v['product']){
                    unset($list[$a]);
                    continue;
                }
        		if($v['add_time']>strtotime(date("Y-m-d 00:00:01"))){
        		    $v['add_time']="今天";
        		}elseif($v['add_time']>strtotime(date("Y-m-d 00:00:00"))-3600*24){
        		    $v['add_time']="昨天";
        		}elseif($v['add_time']>time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600){
        		    $v['add_time']="本周";
        		}elseif($v['add_time']>strtotime(date("Y-m-01 00:00:00"))){
        		    $v['add_time']="本月";
        		}else{
        		    $v['add_time']=date("Y-m",$v['add_time']);
        		}
		    }
		}
        $list = array_values($list);
		$this->success('获取成功',$list);
	}

    //我的钱包
	public function my_rose(){
		$page=$this->request->post('page',1);
		$pagesize=$this->request->post('pagesize',10);
		$month=$this->request->post('month',date("Y-m"));
		$start_time=strtotime($month.'-01');
		$end_time=strtotime($month.'-01 +1 month');
		$add_time=array('between',array($start_time,$end_time));
        $thismonth_1=strtotime(date("Y-m-01 00:00:01"));
		$thismonth_2=strtotime('+1 month',$thismonth_1);
        $thismonth=array('between',array($thismonth_1,$thismonth_2));
		$rose['yue']=$this->user['rose_money'];
		$rose['month_in']=UserRoseLog::where(array('user_id'=>$this->user['id'],'rose_money'=>array('gt',0),'add_time'=>$thismonth))->sum('rose_money');	
		$rose['month_out']=0-UserRoseLog::where(array('user_id'=>$this->user['id'],'rose_money'=>array('lt',0),'add_time'=>$thismonth))->sum('rose_money');	
		$rose['month_log']=UserRoseLog::where(array('user_id'=>$this->user['id'],'add_time'=>$add_time))->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
		foreach($rose['month_log'] as $a=>&$b){
			$v['add_time']=date("Y-m-d H:i:s",$v['add_time']);
		}
        $this->success('获取成功',$rose);
	}

    /**
     * 用户助力
     */
    public function help(){
        $invite_user_id_invite = $this->request->request('invite_user_id_invite','');
        if(!$invite_user_id_invite){
            $this->error('助力参数错误');
        }
        //判断该用户是否已经为该用户助力过
        $redis =redis_init();
        $res = $redis->get($this->user['id'].'help'.$invite_user_id_invite);
        if($res && $res == date('Y-m-d',time())){ //今日已经助力过
            $this->error('不可重复助力');
        }else{
            //今日未助力
            Db::startTrans();
            try {
                $arr = [
                    'user_id'=>$invite_user_id_invite,
                    'title'=>'邀请助力',
                    'type'=>3,
                    'rose_money'=>2,
                    'add_time'=>time()
                ];
                UserRoseLog::insert($arr);
                $user = UserModel::where(['id'=>$invite_user_id_invite])->find();
                UserModel::where(['id'=>$invite_user_id_invite])->update(['rose_money'=>$user['rose_money']+2]);
                $redis->set($this->user['id'].'help'.$invite_user_id_invite,date('Y-m-d',time()));
                Db::commit();
                $this->success('助力成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }
    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

   
    

   

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    //获取二维码
    public function invite_ewm(){
        $mp_id = $this->request->request('mp_id','');
        if(!$mp_id){
            $this->error('参数错误');
        }
        $ewm_img = MpMp::where(['id'=>$mp_id])->value('ewm_img');
        if($ewm_img){
            $this->success('操作成功',$ewm_img);
        }
		$appid='wx84f56a63b9f63e03';
	    $secret='98b698d6f873fdd2292684babd69c975';
		$res= file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
		$tokens=json_decode($res,true);
        if(empty($tokens['access_token'])){
		    $curl = curl_init("https://api.weixin.qq.com/cgi-bin/stable_token");
        	$parameters = json_encode(["grant_type"=>"client_credential", "appid"=>$appid,'secret'=>$secret]);
        	$header = ['Content-type:application/json', 'Accept-Charset:UTF-8'];
        	$options = [
        		CURLOPT_POST => true,
        		CURLOPT_HTTPHEADER => $header,
        		CURLOPT_POSTFIELDS => $parameters,
        		CURLOPT_RETURNTRANSFER => true,
        		CURLOPT_TIMEOUT => 60,
        		CURLOPT_SSL_VERIFYPEER => true,
        		CURLOPT_SSL_VERIFYHOST => 2
        	];
        	curl_setopt_array($curl, $options);
        	$tokens = json_decode(curl_exec($curl),true);
        	curl_close($curl);
	
		}

		$access_token=$tokens['access_token'];
		
		$url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
		$data=array('page'=>'subone/index/user_gr','scene'=>$mp_id,'width'=>120);
		$res = httpRequest($url, $data, "json");
		//二维码图片地址	
		$qr_code ='uploads/invite/'.time().rand(1000, 9999).'.png';
		file_put_contents($qr_code ,$res);
        //$qr_code1 ='uploads/invite/'.time().rand(1000, 9999).'.png';
        //$this->resizeImage($qr_code,$qr_code1, 490, 490,490, 490);
     
        $qr_code= 'https://'.$_SERVER['HTTP_HOST'].'/'.$qr_code;
        MpMp::where(['id'=>$mp_id])->update(['ewm_img'=>$qr_code]);
		$this->success('操作成功',$qr_code);
    }
   
    //获取立即邀请页海报
    public function invite_ewm_shop(){
         //查询该用户总共分享过多少件闲置物品
         $bg="uploads/img/26.jpg";

         $appid = 'wx84f56a63b9f63e03';
         $secret = '98b698d6f873fdd2292684babd69c975';
         //$appid='wx84f56a63b9f63e03';
         //$secret='98b698d6f873fdd2292684babd69c975';
         $res= file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
         $tokens=json_decode($res,true);
         if(empty($tokens['access_token'])){
             $curl = curl_init("https://api.weixin.qq.com/cgi-bin/stable_token");
             $parameters = json_encode(["grant_type"=>"client_credential", "appid"=>$appid,'secret'=>$secret]);
             $header = ['Content-type:application/json', 'Accept-Charset:UTF-8'];
             $options = [
                 CURLOPT_POST => true,
                 CURLOPT_HTTPHEADER => $header,
                 CURLOPT_POSTFIELDS => $parameters,
                 CURLOPT_RETURNTRANSFER => true,
                 CURLOPT_TIMEOUT => 60,
                 CURLOPT_SSL_VERIFYPEER => true,
                 CURLOPT_SSL_VERIFYHOST => 2
             ];
             curl_setopt_array($curl, $options);
             $tokens = json_decode(curl_exec($curl),true);
             curl_close($curl);
     
         }
 
         $access_token=$tokens['access_token'];
         
         $url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
         $data=array('page'=>'pages/shop/shopClass','scene'=>$this->user['id'],'width'=>120);
         $res = httpRequest($url, $data, "json");
         //二维码图片地址	
         $qr_code ='uploads/invite/'.time().rand(1000, 9999).'.png';
         file_put_contents($qr_code ,$res);
         $qr_code1 ='uploads/invite/'.time().rand(1000, 9999).'.png';
         $this->resizeImage($qr_code,$qr_code1, 490, 490,490, 490);
         $image = \think\Image::open($bg);
         $img = 'uploads/invite/'.time().rand(1000, 9999).'.png';
         $image->water($qr_code1,[143,620])->save($img); 
         unlink($qr_code);
         unlink($qr_code1);
         $this->success('操作成功','https://'.$_SERVER['HTTP_HOST'].'/'.$img);
        

    }


    /**
    * 处理图片尺寸【等比例缩小或放大】
    * @param $filePath【进行处理图片本地地址】
    * @param $saveImage【处理后保存地址】
    * @param $maxWidth【最大宽度】
    * @param $maxHeight【最大高度】
    * @param $minWith【最小宽度】
    * @param $minHeight【最小高度】
    */
    function resizeImage($filePath, $saveImage, $maxWidth, $maxHeight, $minWith, $minHeight)
    {
        //获取图片基础信息
        $tmpImageSize = getimagesize($filePath);
        $originalImageWidth = $tmpImageSize[0]; //宽度
        $originalImageHeight = $tmpImageSize[1]; //长度
        $originalImageType = $tmpImageSize[2]; //类型
        //保存图片的宽度跟高度
        $targetWidth = $tmpImageSize[0];
        $targetHeight = $tmpImageSize[1];
        //计算图片将要保存的尺寸
        if ($originalImageWidth > $maxWidth) { //图片宽度超过最大限度
            $targetWidth = $maxWidth;
            $targetHeight = $originalImageHeight * ($maxWidth / $originalImageWidth);
        }
        if ($originalImageWidth < $minWith) { //图片宽带小于最小限度
            $targetWidth = $minWith;
            $targetHeight = $originalImageHeight * ($minWith / $originalImageWidth);
        }
        if ($targetHeight > $maxHeight) { //图片高度超过最大限度
            $targetWidth = $targetWidth * ($maxHeight / $targetHeight);
            $targetHeight = $maxHeight;
        }
        if ($targetHeight < $minHeight) { //图片高度小于最小限度
            $targetWidth = $targetWidth * ($minHeight / $targetHeight);
            $targetHeight = $minHeight;
        }
        //最后检验宽度跟高度是否符合【兜底】
        if ($targetWidth < $minWith) {
            $targetWidth = $minWith;
        }
        if ($targetWidth > $maxWidth) {
            $targetWidth = $maxWidth;
        }
        if ($targetHeight < $minHeight) {
            $targetHeight = $minHeight;
        }
        if ($targetHeight > $maxHeight) {
            $targetHeight = $maxHeight;
        }
        //四舍五入
        $targetWidth = ceil($targetWidth);
        $targetHeight = ceil($targetHeight);
        //判断图片格式进行处理
        if ($originalImageType == 1) {
            $temPic = imagecreatefromgif($filePath);
        } else if ($originalImageType == 2) {
            $temPic = imagecreatefromjpeg($filePath);
        } else if ($originalImageType == 3) {
            $temPic = imagecreatefrompng($filePath);
        } else {
            exit();
        }
        //保存图片
        $thPic = imagecreatetruecolor($targetWidth, $targetHeight);
        // 调整默认颜色
        $color = imagecolorallocate($thPic, 255, 255, 255);
        imagefill($thPic, 0, 0, $color);
        //裁剪
        imagecopyresampled($thPic, $temPic, 0, 0, 0, 0, $targetWidth, $targetHeight,
        $originalImageWidth, $originalImageHeight);
        //保存图片
        imagejpeg($thPic, $saveImage);
    }

    


    
}
